﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MDK.Common.Helper
{
    /// <summary>
    /// 根据ARGB获取颜色
    /// </summary>
    class ColorHelper
    {
        private static Hashtable knownColorsHash;

        public static void InitKnownColorsHash()
        {
            System.Array knownColors = System.Enum.GetValues(typeof(KnownColor));
            Hashtable hashtable = new Hashtable(knownColors.Length);
            foreach (KnownColor knownColorObject in knownColors)
            {
                Color color = Color.FromKnownColor(knownColorObject);
                int argbValue = color.ToArgb();
                if (color.IsSystemColor && hashtable.ContainsKey(argbValue))
                    continue;
                hashtable[argbValue] = knownColorObject;
            }
            knownColorsHash = hashtable;
        }

        public static string TryConvertToKnownColor(Color color)
        {
            KnownColor knownColor = GetKnownColor(color);
            if (knownColor != 0)
            {
                color = Color.FromKnownColor(knownColor);
            }
            return color.Name;
        }

        private static KnownColor GetKnownColor(Color color)
        {
            KnownColor knownColor = color.ToKnownColor();
            if (knownColor == 0)
                knownColor = GetKnownColor(color.ToArgb());
            return knownColor;
        }
        private static KnownColor GetKnownColor(int argb)
        {
            object result = knownColorsHash[argb];
            if (result == null)
                return 0;
            return (KnownColor)result;
        }

        private static KnownColor GetKnownColor(object color)
        {
            if (color is KnownColor)
                return (KnownColor)color;
            if (color is Color)
                return GetKnownColor((Color)color);
            if (color is int)
                return GetKnownColor((int)color);
            return 0;
        }
    }
}
